//
//  Request.m
//  iFlower
//
//  Created by thohd on 7/23/10.
//  Copyright 2010 iNIL.me. All rights reserved.
//

#import "JSON.h"
#import "Request.h"
#import "User.h"
#import "AppDelegate.h"




@implementation Request

@synthesize entries = entries_, delegate = _delegate;
@synthesize flag;
static Request *sharedCLDelegate = nil;

+ (Request *)sharedRequest {
    @synchronized(self) {
        if (sharedCLDelegate == nil) {
            sharedCLDelegate = [Request new]; // assignment not done here
        }
    }
    return sharedCLDelegate;
}

#pragma mark -

- (id) init
{
	if ((self = [super init]) != nil) {
		entries_ = [NSMutableArray new];
		json_ = [NSMutableData new];
	}
	return self;
}

- (void) dealloc
{
	[connection_ release];
	[entries_ release];
	[json_ release];
	[super dealloc];
}

- (void)startConnectionWithURL:(NSURL*)url
{
	if (connection_ == nil)
	{
		NSURLRequest* request = [NSURLRequest requestWithURL: url
												 cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 30.0];
		connection_ = [[NSURLConnection connectionWithRequest: request delegate: self] retain];
		NSLog(@"Request with url:%@",url);
	}	
}

- (NSData *)sendSynchronousRequest: (NSURL*)url 
{
     NSLog(@"Request with url:%@",url);
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url]; 
  
    //[theRequest setHTTPMethod:@"GET"];
    //[theRequest addValue:[NSString stringWithFormat:@"%d",[[postBody dataUsingEncoding:NSUTF8StringEncoding] length]] forHTTPHeaderField:@"Content-Length"];
    //[theRequest setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
    //[theRequest addValue: @"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSURLResponse *response = nil;
    NSError *aError = nil;
    NSData *responseData = nil;
    
    responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&aError];
    return responseData;
}


- (void)post:(NSString*)pageURL withBody:(NSString*)dataBody
{
	if (connection_==nil) {
		NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
		NSLog(@"post to: %@",[NSString stringWithFormat:kBaseURL,pageURL]);
		[request setURL:[NSURL URLWithString:[NSString stringWithFormat:kBaseURL,pageURL]]];
		[request setHTTPMethod:@"POST"];
		//set headers
		NSString *contentType = [NSString stringWithFormat:@"application/x-www-form-urlencoded"];
		[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
		NSLog(@"body:%@",dataBody);
		[request setHTTPBody:[dataBody dataUsingEncoding:NSUTF8StringEncoding]];
		connection_ = [[NSURLConnection connectionWithRequest:request delegate:self] retain];		
	}
	
}
#pragma mark -
#pragma mark NSURLConnection

- (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error
{
	[[NSNotificationCenter defaultCenter] postNotificationName: @"ContentFailed" object: nil];

	[connection_ release];
	connection_ = nil;
}

- (void) connectionDidFinishLoading: (NSURLConnection*) connection
{
	// Parse the JSON and store it into the Catalog
	
	NSString* json = [[[NSString alloc] initWithData: json_ encoding: NSUTF8StringEncoding] autorelease];
	NSLog(@"JSON:%@",json);
	
    entries_ = [json JSONValue];
	
	//[entries_ removeAllObjects];
	//entries_ = [entries copy];
    
    /*
	for (NSDictionary* dictionary in entries)
	{
		[entries_ addObject: dictionary];
	}
    */
	
	// Let others know that the catalog reloaded
	
	[[NSNotificationCenter defaultCenter] postNotificationName: @"ContentLoaded" object: nil];
	
	// Release everything
	
	[connection_ release];
	connection_ = nil;
}

- (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response
{
	[json_ setLength: 0];
}

- (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data
{
    [json_ appendData: data];
}

#pragma mark -
#pragma mark Public methods

- (void)login:(User *)user
{
	[self post:kLoginPage withBody:[user loginData]];
}

-(void) loginByFB:(NSString*)data
{
    [self post:kLoginFB withBody:data];
}
- (void) updateProfile:(User*)user
{
    NSString *url = [NSString stringWithFormat:kUpdateProfile,user.user_id];
	[self post:url withBody:[user updateData]];
}

- (void) getCourses
{
    NSString* url = [NSString stringWithFormat:kBaseURL,kCoursesList];
    NSData* listCourse = [[Request sharedRequest]sendSynchronousRequest:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
    NSString* json = [[[NSString alloc] initWithData: listCourse encoding: NSUTF8StringEncoding] autorelease];
	NSLog(@"JSON:%@",json);
	
    entries_ = [json JSONValue];
    
    
    /*
     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
     dispatch_async(queue, ^{
         NSDictionary *dic = [[[NSDictionary alloc]init]autorelease];
         if ([self.delegate respondsToSelector:@selector(beginLoadCourses:)]) {
             [self.delegate beginLoadCourses:self];
         }
         
         // Tao 1 NSDiction o day
         
         NSData* listCourse;
        listCourse = [[Request sharedRequest]sendSynchronousRequest:[NSURL URLWithString:[kCoursesList stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
         NSString* jsonCourse = [[[NSString alloc] initWithData: listCourse encoding: NSUTF8StringEncoding] autorelease];
         NSLog(@"JSON:%@",json);
         [dic setValue:jsonCourse forKey:@"course"]
         
//         entries_ = [json JSONValue];
//         flag++;
//         if (flag == 3) {
//             [tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
//             [[AppDelegate shareDelegate] hideLoadingView];
//         }
          
         NSData* listModule;
         listModule = [[Request sharedRequest]sendSynchronousRequest:[NSURL URLWithString:[kModulesList stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
         NSString* jsonModule = [[[NSString alloc] initWithData: listModule encoding: NSUTF8StringEncoding] autorelease];
         NSLog(@"JSON:%@",jsonModule);
         
        // sendRequest 1 => duoc data 1 : [dictao tren setValue:data1 forKey:@"data1"
        // sendRequest 2 => duoc data 2 : [dictao tren setValue:data1 forKey:@"data2"
        // sendRequest 3 => duoc data 3 : [dictao tren setValue:data1 forKey:@"data3"
         
         if ([self.delegate respondsToSelector:@selector(endLoadCourses:responseData:)]) {
             [self.delegate endLoadCourses:self responseData:json];
             //[self.delegate endLoadCourses:self responseData:dic tao tren ];             
         }
     });
     */
}

-(void) getModules
{
     NSString* url = [NSString stringWithFormat:kBaseURL,kModulesList];
    NSData* listModule = [[Request sharedRequest]sendSynchronousRequest:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
    NSString* json = [[[NSString alloc] initWithData: listModule encoding: NSUTF8StringEncoding] autorelease];
	NSLog(@"JSON:%@",json);
	
    entries_ = [json JSONValue];
    /*
     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
     dispatch_async(queue, ^{
         NSData* listModule;
         listModule = [[Request sharedRequest]sendSynchronousRequest:[NSURL URLWithString:[kModulesList stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
         NSString* json = [[[NSString alloc] initWithData: listModule encoding: NSUTF8StringEncoding] autorelease];
         NSLog(@"JSON:%@",json);
         
         entries_ = [json JSONValue];
         flag++;
         if (flag == 3) {
             [tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
             [[AppDelegate shareDelegate] hideLoadingView];
         }
     });
     */
     
}

- (void) getColleges
{
    NSString* url = [NSString stringWithFormat:kBaseURL,kCollegesList];
    NSData* listCollege = [[Request sharedRequest]sendSynchronousRequest:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
    NSString* json = [[[NSString alloc] initWithData: listCollege encoding: NSUTF8StringEncoding] autorelease];
	NSLog(@"JSON:%@",json);
	
    entries_ = [json JSONValue];
    /*
     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
     dispatch_async(queue, ^{
         NSData* listCollege;
         listCollege = [[Request sharedRequest]sendSynchronousRequest:[NSURL URLWithString:[kCollegesList stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
         NSString* json = [[[NSString alloc] initWithData: listCollege encoding: NSUTF8StringEncoding] autorelease];
         NSLog(@"JSON:%@",json);
         
         entries_ = [json JSONValue];
         flag++;
         if (flag == 3) {
             [tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
             [[AppDelegate shareDelegate] hideLoadingView];
         }
     });
     */
}
-(void) getPhotos:(User*)user {
    NSString *subURL = [NSString stringWithFormat:kPhotoList,user.user_id];
    NSString* url = [NSString stringWithFormat:kBaseURL,subURL];
    NSData* listImage = [[Request sharedRequest]sendSynchronousRequest:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
    NSString* json = [[[NSString alloc] initWithData: listImage encoding: NSUTF8StringEncoding] autorelease];
	NSLog(@"JSON:%@",json);
	
    entries_ = [json JSONValue];
}

-(void) getPeoples:(NSString*)userId searchBy:(NSString*)searchBy isFav:(NSString*)isFav
{
    //http://demo.vmodev.com/jungoo/index.php/api/people?userId=1&searchBy=nearBy&isFav=false
    NSString *subURL = [NSString stringWithFormat:kPeople,userId,searchBy,isFav];
    NSString* url = [NSString stringWithFormat:kBaseURL,subURL];
    NSData* result = [[Request sharedRequest]sendSynchronousRequest:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
    NSString* json = [[[NSString alloc] initWithData: result encoding: NSUTF8StringEncoding] autorelease];
	NSLog(@"JSON:%@",json);
	
    entries_ = [json JSONValue];
}

-(void)submitfeedback:(NSString*)data
{
    NSLog(@"Data : %@",data);
    [self post:kFeedback withBody:data];
}

- (void)saveUserAvatarWithUserId:(NSString*)userId avatarData:(NSData*)avatarData
{
   
   NSString *urlString = [NSString stringWithFormat:kBaseURL,kUploadPhoto];
   NSURL *url = [NSURL URLWithString:urlString];
   NSString *BOUNDRY = @"---------------------------14737809831466499882746641449";
   NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
   
   [theRequest setHTTPMethod:@"POST"];
   [theRequest setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", BOUNDRY] forHTTPHeaderField:@"Content-Type"];
   
   NSMutableData *body = [NSMutableData dataWithCapacity:[avatarData length] + 512];
   
    /*
   // appId
   [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BOUNDRY] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"appId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[QFC_API_KEY dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   */
   // userId
   [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BOUNDRY] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[userId dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   
   // file
   [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BOUNDRY] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithString:@"Content-Disposition: attachment; name=\"photo\"; filename=\".png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithString:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[NSData dataWithData:avatarData]];
   [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   
   // close form
   [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BOUNDRY] dataUsingEncoding:NSUTF8StringEncoding]];
   
   // set request body
   [theRequest setHTTPBody:body];
   
   NSURLResponse *response = nil;
   NSError *aError = nil;
   NSData *responseData = nil;
   
   responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&aError];
    NSString* json = [[[NSString alloc] initWithData: responseData encoding: NSUTF8StringEncoding] autorelease];
	NSLog(@"JSON:%@",json);
	
    entries_ = [json JSONValue];
   /*
   if (aError != nil || response == nil) {
        QFC_API_HANDLE_ERROR(QFC_ERROR_CODE_NETWORK,
                                   QFC_ERROR_MSG_NETWORK);
        return nil;
        }
    else {
        [responseData writeToFile:@"/QFC/saveUserAvatar.txt" atomically:YES];
        NSString *responseString = [[[NSString alloc] initWithBytes:[responseData bytes] 
                                             length:[responseData length] 
                                             encoding:NSUTF8StringEncoding] autorelease];
       
       
       if ([responseString isKindOfClass:[NSString class]]) {
           NSDictionary *dictResponse = [responseString JSONValue];
        
           if (dictResponse == nil) {
                QFC_API_HANDLE_ERROR(QFC_ERROR_CODE_DATA,QFC_ERROR_MSG_DATA);
                return nil;
            }
            else {
                if ([[dictResponse objectForKey:@"return_code"] isEqualToString:@"0"]) {
                    return [dictResponse objectForKey:@"url"];
                    }  
                else {
                    QFC_API_HANDLE_ERROR(QFC_ERROR_CODE_UNKNOW,QFC_ERROR_MSG_UNKNOW);
                    return nil;
                 }
             }
        }
    }

    QFC_API_HANDLE_ERROR(QFC_ERROR_CODE_UNKNOW,QFC_ERROR_MSG_UNKNOW);
    */    
}
/*
- (void) registerUser:(User*)user
{
	[self post:kRegisterUserPattern withBody:[user registerData]];
}
 */
@end
